import React from 'react'
import { connect } from 'dva'
import styles from './DepartmentManager.less'
import { Button, Form, Tree, Skeleton, Alert } from 'antd'
import Header from '../../components/Header/index'
import PropTypes from 'prop-types'
import gql from 'graphql-tag'
import { GQL as AGQL } from '../../components/GQL'
import Todo from './components/Todo'
import DepartMentMoadl from './components/Modal'

const headerData = {
  title: '部门管理',
  hasPopover: true,
  popoverContent: <p style={{ fontSize: 13 }}>设置你们公司部门划分，比如：销售1部 销售2部 仓管部 采购部 财务部</p>, // 上面为true，则填写,可直接写html代码，不用引号包含，可选
  hasSubNav: true,
  subNavItem: [
    {
      title: '首页',
      link: true
    },
    {
      title: '系统',
      link: false
    },
    {
      title: '账号管理',
      link: true
    }
  ]
}
const { TreeNode } = Tree

class DepartmentManager extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      gData: [],
      expandedKeys: []
    }
  }
  onDragEnter (info) {
    console.log(info)
    // expandedKeys 需要受控时设置
    // this.setState({
    //   expandedKeys: info.expandedKeys,
    // });
  }

  onDrop (info) {
    const { data: { departments = [] }, updateQuery } = this.props
    const dropKey = info.node.props.eventKey
    const dragKey = info.dragNode.props.eventKey
    const dropPos = info.node.props.pos.split('-')
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])

    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.id === parseInt(key)) {
          return callback(item, index, arr)
        }
        if (item.children) {
          return loop(item.children, key, callback)
        }
      })
    }
    // Find dragObject
    let dragObj
    loop(departments, dragKey, (item, index, arr) => {
      arr.splice(index, 1)
      dragObj = item
    })
    if (!info.dropToGap) {
      // Drop on the content
      loop(departments, dropKey, (item) => {
        item.children = item.children || []
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.push(dragObj)
      })
    } else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(departments, dropKey, (item) => {
        item.children = item.children || []
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.unshift(dragObj)
      })
    } else {
      let ar
      let i
      loop(departments, dropKey, (item, index, arr) => {
        ar = arr
        i = index
      })
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj)
      } else {
        ar.splice(i + 1, 0, dragObj)
      }
    }

    updateQuery((previousQueryResult, { variables }) => {
      previousQueryResult.departments = departments
      console.log(previousQueryResult.departments)
      return previousQueryResult
    })
  }

  render () {
    const { data = {}, departmentManager = {}, loading, dispatch, refetch } = this.props
    const { departments = [] } = data
    const { departs } = departmentManager
    const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <TreeNode blockNode style={{ paddingRight: 15 }} key={item.id} title={<Todo title={item.name} record={item} refetch={refetch} />}>{loop(item.children)}</TreeNode>
      }
      return <TreeNode blockNode key={item.id} title={<Todo title={item.name} record={item} refetch={refetch} />} />
    })

    return (
      <div className={styles.container}>
        <DepartMentMoadl visible={departmentManager.visible} refetch={refetch} departments={departments} departs={departs} />
        <Header header={headerData} />
        <div className={styles.content}>
          <div className={styles.distance}>
            <Button type='primary' onClick={() => dispatch({ type: 'departmentManager/save', payload: { visible: true, departs: {} } })}>新增部门</Button>&nbsp;&nbsp;&nbsp;
            {/* 展开收起 */}
            <Button onClick={() => dispatch({ type: 'departmentManager/save', payload: { flag: !departmentManager.flag } })}>
              {departmentManager.flag ? '展开' : '收起' }
            </Button>
          </div>
          <div style={{ marginTop: 20, marginLeft: 20, width: 1000 }}>
            <Alert
              description='1、可以拖动某条内容上下移动修改顺序； 2、修改请勿忘保存'
              type='warning'
              showIcon
            />
          </div>
          <div style={{ margin: 20 }}>
            <div>
              <Skeleton active loading={loading}>
                <Tree
                  defaultExpandAll={false}
                  className='draggable-tree'
                  draggable
                  blockNode
                  showLine
                  onDragEnter={this.onDragEnter}
                  onDrop={this.onDrop.bind(this)}
                >
                  {loop(departments)}
                </Tree>
              </Skeleton>
            </div>
          </div>
        </div>
        <div className={styles.bottom}>
          <Button type='primary'>保存顺序</Button>
          <Button>取消</Button>
        </div>
      </div>
    )
  }
}

DepartmentManager.propTypes = {
  departmentManager: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.bool,
  data: PropTypes.object,
  updateQuery: PropTypes.func,
  refetch: PropTypes.func
}
const mapStateToProps = ({ departmentManager }) => ({ departmentManager })

export default AGQL({
  query: gql`
    query{
      departments{
        id
        name
        children{
          id
          name
          children {
            id
            name
          }
        }
      }
    }
    `,
  fetchPolicy: 'no-cache',
  notifyOnNetworkStatusChange: true
})(connect(mapStateToProps)(Form.create()(DepartmentManager)))
